import db from '@/mock/createDB'
import Mock from 'mockjs'
import { parseUrl } from '@/utils/toolFunction'

// 所有角色查询
Mock.mock('/roles/all', 'get', () => {
  const result = db.select('roles_table', (item:any) => {
    return true;
  })
  return { code: 0, message: '查询成功', data: result }
})

// 添加角色
Mock.mock('/roles/create', 'post', ({ body }) => {
  let { roleName } = JSON.parse(body);
  const nameRepeat = db.select('roles_table', (item:any) => item.roleName === roleName)
  // 判断角色名称是否存在
  if (nameRepeat && nameRepeat.length) {
    return {
      code: 1010,
      message: '该角色已存在'
    }
  }
  db.add('roles_table', { roleName })
  return {
    code: 0,
    message: '添加成功'
  }
})

// 修改修改
Mock.mock('/roles/modify', 'post', ({ body }) => {
  let { id, roleName } = JSON.parse(body);
  // 数字的转为数字
  id = +id;
  const result = db.select('roles_table', item => item.id === id)[0];
  const { roleName: _roleName } = result;
  const nameRepeat = db.select('roles_table', (item:any) => item.roleName === roleName && item.roleName !== _roleName && roleName);
  // 判断角色名称是否被使用
  if (nameRepeat && nameRepeat.length) {
    return {
      code: 1010,
      message: '该角色已存在'
    }
  }
  const row = { id, roleName };
  db.put('roles_table', id, row);
  return {
    code: 0,
    message: '修改成功'
  }
})

// 删除部门
Mock.mock(/roles\/delete(\?.+)?/, 'get', ({ url }) => {
  //@ts-ignore
  let id = parseUrl(url).id;
  id = +id;
  console.log(id);
  db.delete('roles_table', id)
  return {
    code: 0,
    message: '删除成功'
  }
})

